package xnote

import (
	"fmt"
	"strings"
	"time"

	"gitee.com/xiaoyutab/xgotool/optional/xlog"
	"gitee.com/xiaoyutab/xgotool/xerror"
	"gitee.com/xiaoyutab/xgotool/xnum"
)

// 添加Menu中的menu_id
//
//	id	菜单id
//	uid	用户ID
//	mid	menu_id
func CreateMenuId(id, uid, mid uint) error {
	if _default.DB == nil {
		return xerror.New("数据库未连接")
	}
	// 获取menu记录信息
	menu := NoteMenu{}
	err := _default.DB.Table(_default.MenuName).
		Where("id", id).
		Where("user_id", uid).
		Where("is_deleted", 0).
		Find(&menu).
		Error
	if err != nil {
		return xlog.AE("菜单信息未找到", err)
	}
	if menu.Id == 0 {
		return xerror.New("记录未找到")
	}
	// 查询menu_ids
	menu_ids := strings.Split(menu.MenuId, ",")
	mm_id := fmt.Sprintf("%d", mid)
	if xnum.InArray(mm_id, menu_ids) {
		return xerror.New("该条目已添加")
	}
	menu_ids = append(menu_ids, mm_id)
	menu.MenuId = strings.Join(menu_ids, ",")
	menu.UpdatedAt = time.Now().Format(time.DateTime)
	err = _default.DB.Table(_default.MenuName).
		Where("id", id).
		Where("user_id", uid).
		Where("is_deleted", 0).
		Select("menu_id", "updated_at").
		Updates(&menu).
		Error
	if err != nil {
		return xlog.AE("菜单信息存储失败", err)
	}
	return nil
}
